          //
//  DatabaseHandle.m
//  WatchBallSqlite
//
//  Created by lanou3g on 15/6/5.
//  Copyright (c) 2015年 lanou3g. All rights reserved.
//
#import <sqlite3.h>
#import "DatabaseHandle.h"
#import "Model.h"
#define ARCHIVERKEY @"archiver"
#import <UIKit/UIKit.h>
static DatabaseHandle *dataHandle =nil;


@implementation DatabaseHandle
+ (DatabaseHandle*)shardInstnce{
    @synchronized(self){
        if (dataHandle == nil) {
            dataHandle = [[DatabaseHandle alloc]init];
            
        }
        return dataHandle;
    }
}

//打开数据库
static sqlite3 *db = nil;
- (void)openDB{
    
    if (db !=nil||self.fileName ==nil) {
        return;
    }
    
    NSString *filePath = [self useDocumentPathSqlite:self.fileName];
  
    
    int result = sqlite3_open(filePath.UTF8String,&db);
    if (result ==SQLITE_OK) {
        NSString *createModelSql = @"CREATE TABLE ModelList(ID TEXT PRIMARY KEY,data BLOB)";
        //执行参数?
        sqlite3_exec(db, [createModelSql UTF8String], NULL, NULL, NULL);
    }
    
}

- (void)closeDB{
    int result = sqlite3_close(db);
    if (result ==SQLITE_OK) {
        db = nil;
    
    }
}

//插入收藏活动

- (void)insertNewactivity:(Model *)model{
    [self openDB];
    static sqlite3_stmt *stmt = nil;
    NSString *sql = @"insert into ModelList(ID,data) values (?,?)";
    int result = sqlite3_prepare_v2(db, sql.UTF8String, -1, &stmt, nil);
    
    if (result ==SQLITE_OK) {
        sqlite3_bind_text(stmt, 1, [model.ID UTF8String], -1, nil);

        
        NSString *archiverKey = [NSString stringWithFormat:@"%@%@",ARCHIVERKEY,model.ID];
        NSData *data = [self dataOfArchiverObject:model forKey:archiverKey];
        sqlite3_bind_blob(stmt, 2, [data bytes], (int)[data length], nil);
        
        sqlite3_step(stmt);
        
        CGFloat version = [[[UIDevice currentDevice] systemVersion] floatValue];
        
        if (version>=8.0) {
            UIAlertController *alertC = [UIAlertController alertControllerWithTitle:@"提示" message:@"收藏成功!" preferredStyle:UIAlertControllerStyleAlert];
            [self.viewController presentViewController:alertC animated:YES completion:nil];
            [self performSelector:@selector(dismissAlertC:) withObject:alertC afterDelay:1];

        }else{
            UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"提示" message:@"收藏成功!" delegate:nil cancelButtonTitle:nil otherButtonTitles:nil, nil];
            [alertView show];
            [self performSelector:@selector(dismissAlertView:) withObject:alertView afterDelay:1];
        }
        
        
        
    }
    
    sqlite3_finalize(stmt);
    [self closeDB];
}
- (void)dismissAlertC:(UIAlertController*)alertC{
    [self.viewController dismissViewControllerAnimated:alertC completion:nil];
}
- (void)deleteModelByID:(NSString *)ID{
    
    [self openDB];
    
    NSString *deleteSQL = [NSString stringWithFormat:@"delete from ModelList where ID ='%@'",ID];
    
    char * error =nil;
    
    int result = sqlite3_exec(db, deleteSQL.UTF8String, NULL, NULL, &error);
    
    if (result == SQLITE_OK) {
        
        
        
    }else{
        
      
        
    }
  
    
}




- (Model*)selectModelWithID:(NSString *)ID{
    [self openDB];
    
    sqlite3_stmt *stmt = nil;
    
    NSString *sql = @"select data from ModelList where ID = ?";
    
    int result = sqlite3_prepare_v2(db, [sql UTF8String], -1, &stmt, NULL);
    
    Model *model = nil;
    
    if (result ==SQLITE_OK) {
        sqlite3_bind_text(stmt, 1, [ID UTF8String], -1, NULL);
        if (sqlite3_step(stmt) ==SQLITE_ROW) {
            
            
            NSData *data = [NSData dataWithBytes:sqlite3_column_blob(stmt, 0) length:sqlite3_column_bytes(stmt, 0)];
            
            NSString *archiver = [NSString stringWithFormat:@"%@%@",ARCHIVERKEY,ID];
            model = [self unarchiverObject:data forKey:archiver];
 
        }
    }
    sqlite3_finalize(stmt);
    [self closeDB];
    return model;
    
}

- (NSArray*)selectAllModel{
    [self openDB];
    
    sqlite3_stmt *stmt = nil;
    NSString *sql = @"select ID,data from ModelList";
   
    
    int result = sqlite3_prepare_v2(db, [sql UTF8String], -1, &stmt, NULL);
    
    NSMutableArray *activityArray = [NSMutableArray array];
    
    
    if (result == SQLITE_OK) {
        
        while (sqlite3_step(stmt) ==SQLITE_ROW) {
                     NSString *ID = [NSString stringWithUTF8String:(const char*)sqlite3_column_text(stmt, 0)];
            NSData *data = [NSData dataWithBytes:sqlite3_column_blob(stmt, 1) length:sqlite3_column_bytes(stmt, 1)];
            NSString *modelKey = [NSString stringWithFormat:@"%@%@",ARCHIVERKEY,ID];
            
            Model * model = [self unarchiverObject:data forKey:modelKey];
            [activityArray addObject:model];
          
            
        }
    }
    sqlite3_finalize(stmt);
    [self closeDB];
    if (activityArray.count ==0) {
        return nil;
    }
    return activityArray;
}

- (BOOL)isFavoriteModelWithID:(NSString *)ID{
    
    Model *model = [self selectModelWithID:ID];
    if (model ==nil) {
       
        return NO;
        
    }
    //--------判断版本--------
    float version = [[[UIDevice currentDevice] systemVersion] floatValue];
    if ( version>=8.0) {
    
    if (model) {
        
        UIAlertController * alertC = [UIAlertController alertControllerWithTitle:@"提示" message:@"您已经收藏过该条目" preferredStyle:(UIAlertControllerStyleAlert)];
        [self.viewController presentViewController:alertC animated:YES completion:nil];
        [self performSelector:@selector(dismissAlertC:) withObject:alertC afterDelay:0.5];
              }
    }else{
        if (model) {
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"您已经收藏过该条目" delegate:nil cancelButtonTitle:nil otherButtonTitles:nil, nil];
        [alert show];
        [self performSelector:@selector(dismissAlertView:) withObject:alert afterDelay:0.5];
        }
    }
    return YES;
}
- (void)dismissAlertView:(UIAlertView*)alert{
    [alert dismissWithClickedButtonIndex:0 animated:YES];
}


#pragma ---文件路径处理----
////文件夹路径处理
- (NSString*)useCachesPathSqlite:(NSString*)databaseName{
    
    NSString *caches = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).lastObject;
    
    NSString *filePath = [caches stringByAppendingPathComponent:databaseName];
    return filePath;
}
#pragma ---归档处理---
- (NSData *)dataOfArchiverObject:(id)object forKey:(NSString*)key{
    NSMutableData *data = [NSMutableData data];
    
    NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc]initForWritingWithMutableData:data];
    [archiver encodeObject:object forKey:key];
    [archiver finishEncoding];
    return data;
    
}

- (id)unarchiverObject:(NSData*)data forKey:(NSString *)key{
    NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc]initForReadingWithData:data];
    
    id object = [unarchiver decodeObjectForKey:key];
    [unarchiver finishDecoding];
    
    return object;
}

- (NSString *)useDocumentPathSqlite:(NSString*)databaseName{
    NSString *document = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject;
    NSString *filePath = [document stringByAppendingPathComponent:databaseName];
    return filePath;
}

@end
